package com.hangzhou.xyj.push;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.db.GroupPushMsgDao;
import com.hangzhou.xyj.db.preferences.CommonPreferences;
import com.hangzhou.xyj.manager.NotifyManager;
import com.hangzhou.xyj.model.GroupPushMsgModel;
import com.hangzhou.xyj.model.MessageModel;
import com.hangzhou.xyj.model.type.EGroupPushType;
import com.hangzhou.xyj.model.type.EPushMessageType;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.constants.DataKey;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * <p/>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";


    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) {
                    Log.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
//        PushService service = new PushService();
        Bundle bundle = intent.getExtras();
        Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            processCustomMessage(context, bundle, message);
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
            String message = bundle.getString(JPushInterface.EXTRA_ALERT);
            String path = parseExtraBundle(bundle);
            saveMessage(context, message + path);
//            processCustomMessage(context, bundle);
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
            String message = bundle.getString(JPushInterface.EXTRA_ALERT);
            String path = parseExtraBundle(bundle);
            Intent i = new Intent(context, NotificationReceiver.class);
            i.putExtra(DataKey.URL, path);
            i.putExtra(DataKey.MESSAGE, message);
//            i.putExtra(DataKey.PUSH_TYPE, EPushMessageType.SYSTEM.getValue());
            context.sendBroadcast(i);//发送广播
//            if (StringUtil.isNotEmpty(CommonPreferences.getUserId(context))) {//已经登录，都跳转到我的消息界面
//                i = new Intent(context, MyMessageActivity.class);
//                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                context.startActivity(i);
//            } else {//未登录
//                if (StringUtil.isNotEmpty(path)) {
//                    i = new Intent(context, WebActivity.class);
//                    i.putExtra(DataKey.TITLE, message);
//                    i.putExtra(DataKey.INDEX, path);
//                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    context.startActivity(i);
//                } else {
//                    i = new Intent(context, MyOfficalMessageActivity.class);
//                    GroupPushMsgModel msgModel = new GroupPushMsgModel();
//                    msgModel.setMsgTime(System.currentTimeMillis());//时间
//                    msgModel.setGroupPic("drawable://" + R.drawable.ic_offical_head);//头像
//                    msgModel.setMsgType(EGroupPushType.NOTIFICATION.getValue());//类型
//                    msgModel.setContent(message);
//                    msgModel.setToId("all");
//                    i.putExtra(DataKey.OBJ, msgModel);
//                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    context.startActivity(i);
//                }
//            }
//            saveMessage(context, message + path);
        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Log.w(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
        } else {
            Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    /**
     * 处理自定义消息
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/6/7 15:31
     */
    private void processCustomMessage(Context context, Bundle bundle, String message) {
        String url = parseExtraBundle(bundle);//解析出url
        Intent i = new Intent(context, NotificationReceiver.class);
        i.putExtra(DataKey.URL, url);
        i.putExtra(DataKey.MESSAGE, message);
//        context.sendBroadcast(i);//发送广播
//        if (XYJApplication.getUserInfo() != null) {//已经登录，跳转到我的消息
//            intent = new Intent(context, MyMessageActivity.class);
//            NotifyManager.getInstance().notify(context, new MessageModel(EPushMessageType.SYSTEM.getValue(),
//                    System.currentTimeMillis()), intent);//通知一条系统消息
//        } else {//未登录
//            if (StringUtil.isNotEmpty(url)) {
//                intent = new Intent(context, WebActivity.class);
//                intent.putExtra(DataKey.INDEX, url);
//                intent.putExtra(DataKey.TITLE, message);
//                intent.putExtra(DataKey.PUSH_TYPE, EPushMessageType.SYSTEM.getValue());
//            } else {
//                intent = new Intent(context, MyOfficalMessageActivity.class);
//                GroupPushMsgModel msgModel = new GroupPushMsgModel();
//                msgModel.setMsgTime(System.currentTimeMillis());//时间
//                msgModel.setGroupPic("drawable://" + R.drawable.ic_offical_head);//头像
//                msgModel.setMsgType(EGroupPushType.NOTIFICATION.getValue());//类型
//                msgModel.setContent(message);
//                msgModel.setToId("all");
//                intent.putExtra(DataKey.OBJ, msgModel);
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            }
        NotifyManager.getInstance().notify(context, new MessageModel(EPushMessageType.SYSTEM.getValue(),
                System.currentTimeMillis()), i);//通知一条系统消息
//        }
        //保存
        saveMessage(context, message + url);
//        this.abortBroadcast();
//        String url = "";
//        JPushInterface.setDefaultPushNotificationBuilder(new BasicPushNotificationBuilder(context));
//        String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
//        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//        if (StringUtil.isNotEmpty(extras)) {
//            JsonElement jsonElement = new JsonParser().parse(extras);
//            url = jsonElement.getAsJsonObject().get("url").toString();
//        }

//        if (StringUtil.isNotEmpty(url)) {
//            intent = new Intent(context, WebActivity.class);
//            intent.putExtra(DataKey.INDEX, url);
//        } else {
//        }
//        MessageModel mm = new MessageModel(EPushMessageType.SYSTEM.getValue(), System.currentTimeMillis());
//        NotifyManager.getInstance().notify(context, mm, intent);
//        MessageDao messageDao = new MessageDao(context);
//        messageDao.addMessage(mm);
//		if (MainActivity.isForeground) {
//			String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
//			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//			Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
//			msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);
//			if (!ExampleUtil.isEmpty(extras)) {
//				try {
//					JSONObject extraJson = new JSONObject(extras);
//					if (null != extraJson && extraJson.length() > 0) {
//						msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras);
//					}
//				} catch (JSONException e) {
//				}
//			}
//			context.sendBroadcast(msgIntent);
//		}
    }

//    /**
//     * 打开通知之后
//     *
//     * @param
//     * @return
//     * @author yaohuix
//     * @date 2016/6/7 15:21
//     */
//    public void doSome(Context context, Bundle bundle, String message) {
//        String htmlPath = parseExtraBundle(bundle);
//        //解析消息的内容
////        String message = bundle.getString(JPushInterface.EXTRA_ALERT);
//        Intent i;
//        if (StringUtil.isNotEmpty(htmlPath)) {
//            i = new Intent(context, WebActivity.class);
//            i.putExtra(DataKey.TITLE, message);
//            i.putExtra(DataKey.INDEX, htmlPath);
//            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            context.startActivity(i);
//        }
//        saveMessage(context, message);
//    }

    /**
     * 解析出url
     *
     * @param
     * @return 附加的url
     * @author yaohuix
     * @date 2016/6/7 15:35
     */
    private String parseExtraBundle(Bundle bundle) {
        //解析附加数据
        String extraExtra = bundle.getString(JPushInterface.EXTRA_EXTRA);
        String htmlPath = "";
        JSONObject json = null;
        if (StringUtil.isNotEmpty(extraExtra)) {
            try {
                json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                Iterator<String> it = json.keys();
                while (it.hasNext()) {
                    String myKey = it.next().toString();
                    if ("url".equals(myKey)) {
                        htmlPath = json.optString(myKey);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return htmlPath;
    }

    /**
     * 保存消息
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/6/7 15:33
     */
    private void saveMessage(Context context, String message) {
        if (Integer.valueOf(CommonPreferences.getUserId(context)) != -1) {//如果已经登录，保存数据
            GroupPushMsgModel msgModel = new GroupPushMsgModel();
            msgModel.setMsgTime(System.currentTimeMillis());//时间
            msgModel.setGroupPic("drawable://" + R.drawable.ic_offical_head);//头像
            msgModel.setMsgType(EGroupPushType.NOTIFICATION.getValue());//类型
            msgModel.setContent(message);
            msgModel.setToId("all");
            //保存到本地数据库
            GroupPushMsgDao dao = new GroupPushMsgDao(context);
            dao.add(msgModel);
        }
    }
}
